package com.kjs.common.tools;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 散列封装
 * @author wujr
 *
 */
public class MD {
	/**
	 * 计算字符串的md5值
	 * @param src
	 * @return 16进制的字符串，小写
	 */
	public static String md5(String src){
		byte[] byteArray = null;
        try {
            byteArray = src.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }

        byte[] md5Bytes = md5(byteArray);
        return StringCodec.bin2hex(md5Bytes);
	}
	public static String md(String src, String algorithm){
		byte[] byteArray = null;
        try {
            byteArray = src.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }

        byte[] md5Bytes = md(byteArray, algorithm);
        return StringCodec.bin2hex(md5Bytes);
	}
	
	public static byte[] md5(byte[] src){
		return md(src, "MD5");
	}
	public static byte[] sha1(byte[] src){
		return md(src, "SHA-1");
	}
	
	/**
	 * 
	 * @param src
	 * @param algorithm: MD5,SHA-1
	 * @return
	 */
	public static byte[] md(byte[] src, String algorithm){
		MessageDigest md = null;
		try{
			md = MessageDigest.getInstance(algorithm);
		}catch(NoSuchAlgorithmException e){
			e.printStackTrace();
			return null;
		}
		return md.digest(src);
	}
}
